from flask import Flask
from flask_cors import CORS
import os
from .extensions import db

def create_app(test_config=None):
    app = Flask(__name__)
    
    # 配置
    basedir = os.path.abspath(os.path.dirname(__file__))
    db_path = os.path.join(os.path.dirname(basedir), 'instance', 'ams.db')
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'dev')
    
    # 初始化扩展
    db.init_app(app)
    
    # 更新CORS配置，设置更宽松的跨域规则
    CORS(app, resources={r"/api/*": {
             "origins": "*",  # 允许所有来源
             "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
             "allow_headers": ["Content-Type", "Authorization"],
             "supports_credentials": True
         }})
    
    # 注册蓝图
    from .api import (
        airports, runways, parking_aprons, oil_tanks,
        ammunition_depots, aircraft, external_facilities,
        analysis, oil_supply, ammunition_supply, protection
    )
    
    # 注册所有蓝图
    app.register_blueprint(airports)
    app.register_blueprint(runways)
    app.register_blueprint(parking_aprons)
    app.register_blueprint(oil_tanks)
    app.register_blueprint(ammunition_depots)
    app.register_blueprint(aircraft)
    app.register_blueprint(external_facilities)
    app.register_blueprint(analysis)
    app.register_blueprint(oil_supply)
    app.register_blueprint(ammunition_supply)
    app.register_blueprint(protection)
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
    
    return app 